 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.dto.SwCkClearRulesDTO;
import com.zdkj.subway.rca.dto.in.OneSidedSales;
import com.zdkj.subway.rca.dto.in.OneSidedSalesDTO;
import com.zdkj.subway.rca.dto.out.SwCkClearRulesExcelDTO;
import com.zdkj.subway.rca.entity.*;
import com.zdkj.subway.rca.enums.SwCkClearRuleConstans;
import com.zdkj.subway.rca.mapper.SwCkClearRulesMapper;
import com.zdkj.subway.rca.service.*;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import com.zdkj.subway.rca.util.MyDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 清分规则管理
 *
 * @author stw
 * @date 2020-11-08 22:46:57
 *
 */
@Service
public class SwCkClearRulesServiceImpl extends ServiceImpl<SwCkClearRulesMapper, SwCkClearRules> implements SwCkClearRulesService {
    private static final Logger log = LoggerFactory.getLogger(SwCkClearRulesServiceImpl.class);
    @Autowired
    private SwCkClearRulesLineService swCkClearRulesLineService;
    @Autowired
    private SwCkSysCleaningConsTicketService swCkSysCleaningConsTicketService;
    @Autowired
    private TconscleanService tconscleanService;
    @Autowired
    private SwCkSysCleaningConsTypeService swCkSysCleaningConsTypeService;
    @Autowired
    private SwCkSystemCleanViewService swCkSystemCleanViewService;


    @Override
    public List<Map<String,String>> getServiceMap(){
        return this.baseMapper.selectServiceMap();
    }
    @Override
    public String getServiceName (String serviceId) {
        List<Map<String,String>> serviceMap = getServiceMap();
        for (Map<String,String> map : serviceMap){
            if(serviceId.equals(map.get("operators"))){
                return map.get("operatorsName");
            }
        }
        return "";
    }

    private String getLineName (List<Map<String,String>>  lineMap, String lineCode) {
        for (Map<String,String> map : lineMap){
            if(lineCode.equals(map.get("CODE"))){
                return map.get("NAME");
            }
        }
        return "";
    }

    //查清分规则name
    private List<Map<String, String>> getClearRules() {
        return this.baseMapper.selectClearRulesMap();
    }
    private String listClearRules(String clearRules) {
        List<Map<String,String>> clearRulesMap = getClearRules();
        for (Map<String,String> map : clearRulesMap){
            if(clearRules.equals(map.get("value"))){
                return map.get("label");
            }
        }
        return "";

    }

    //查子清分规则name
    private String SubClearRulesAll(String clearRules, String subClearRules) {
        List<Map<String,String>> SubClearRulesMap = getSubClearRules(clearRules);
        for (Map<String,String> map : SubClearRulesMap){
            if(subClearRules.equals(map.get("value"))){
                return map.get("label");
            }
        }
        return "";
    }

    private List<Map<String, String>> getSubClearRules(String clearRules) {
        return this.baseMapper.selectSubClearRulesMap(clearRules);
    }


    /**
     * 新增
     * @param swCkClearRulesDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSwCkClearRules(SwCkClearRulesDTO swCkClearRulesDTO) {
        //获取公共属性
        SwCkClearRules swCkClearRules = swCkClearRulesDTO.getDatas();
        List<SwCkClearRules> oneList = list(Wrappers.<SwCkClearRules>lambdaQuery()
                .eq(SwCkClearRules::getBeginTime, swCkClearRules.getBeginTime())
                .eq(SwCkClearRules::getEndTime, swCkClearRules.getEndTime())
                .eq(SwCkClearRules::getClearRules, swCkClearRules.getClearRules())
                .eq(StringUtils.isNotEmpty(swCkClearRules.getSubClearRules()), SwCkClearRules::getSubClearRules, swCkClearRules.getSubClearRules())
                .eq(StringUtils.isNotEmpty(swCkClearRules.getOperators()), SwCkClearRules::getOperators, swCkClearRules.getOperators())
                .eq(SwCkClearRules::getUsedState, "1")//查已启用
                .eq(SwCkClearRules::getDelFlag, "0")
        );
        //存在相同数据，然后根据启用状态来判断（开始-结束-清分规则-运营商） 来判断
        if(CollectionUtil.isNotEmpty(oneList)){
            //如果启用状态都是已使用，更改旧的启用状态 否则不做处理
            if("1".equals(swCkClearRules.getUsedState())){
                oneList.forEach(x -> x.setUsedState("2"));//未启用
                updateBatchById(oneList);
            }
        }
        ObjectUtils.setDefaultFiledValueOfBelongToLine(swCkClearRules);
        //保存主表
        String uuid = UUID.randomUUID().toString().toLowerCase();
        swCkClearRules.setUuid(uuid);
        swCkClearRules.setDataSource("2");//手工添加
        save(swCkClearRules);

        //子表
        List<SwCkClearRulesLine> details = swCkClearRulesDTO.getDataDetails();
        if (CollectionUtil.isNotEmpty(details)) {
            for (SwCkClearRulesLine detail : details) {
                ObjectUtils.setDefaultFiledValueOfBelongToLine(detail);
            }
            //保存从表
            details.forEach(x -> x.setRuleId(swCkClearRules.getUuid()));
            swCkClearRulesLineService.saveBatch(details);
        }
        return true;

    }

    /**
     * 修改
     * @param swCkClearRulesDTO
     * @return
     */
    @Override
    public boolean updateSwCkClearRules(SwCkClearRulesDTO swCkClearRulesDTO) {
        SwCkClearRules swCkClearRules = swCkClearRulesDTO.getDatas();
        List<SwCkClearRules> oneList = list(Wrappers.<SwCkClearRules>lambdaQuery()
                .eq(SwCkClearRules::getBeginTime, swCkClearRules.getBeginTime())
                .eq(SwCkClearRules::getEndTime, swCkClearRules.getEndTime())
                .eq(SwCkClearRules::getClearRules, swCkClearRules.getClearRules())
                .eq(StringUtils.isNotEmpty(swCkClearRules.getSubClearRules()), SwCkClearRules::getSubClearRules, swCkClearRules.getSubClearRules())
                .eq(StringUtils.isNotEmpty(swCkClearRules.getOperators()), SwCkClearRules::getOperators, swCkClearRules.getOperators())
                .eq(SwCkClearRules::getUsedState, "1")//查已启用
                .eq(SwCkClearRules::getDelFlag, "0")
                .ne(SwCkClearRules::getId,swCkClearRules.getId())
        );
        //存在相同数据，然后根据启用状态来判断（开始-结束-运营商） 来判断
        if(CollectionUtil.isNotEmpty(oneList)){
            //如果启用状态都是已使用，更改旧的启用状态 否则不做处理
            if("1".equals(swCkClearRules.getUsedState())){
                oneList.forEach(x -> x.setUsedState("2"));//未启用
                updateBatchById(oneList);
            }
        }
        String uuid = swCkClearRules.getUuid();
        //更新主表
        updateById(swCkClearRules);
        List<SwCkClearRulesLine> details = swCkClearRulesDTO.getDataDetails();
        if(CollectionUtil.isNotEmpty(details)){
            //更新从表  需要注意点是 从表是有可能有新增数据的
            List<SwCkClearRulesLine> updateData = new ArrayList<>();
            List<SwCkClearRulesLine> insertData = new ArrayList<>();
            // 将新增的数据统计出来
            for (SwCkClearRulesLine detail : details) {
                if (detail.getId() != null) {
                    updateData.add(detail);
                } else {
                    detail.setRuleId(swCkClearRules.getUuid());
                    insertData.add(detail);
                }
            }
            //删除已经在界面删除的数据
            List<Long> updateIds = updateData.stream().map(x -> x.getId()).collect(Collectors.toList());
            List<SwCkClearRulesLine> rulesLinesRemoveList = new ArrayList<>();
            List<SwCkClearRulesLine> rulesLinesDeatails = swCkClearRulesLineService.list(new QueryWrapper<SwCkClearRulesLine>()
                    .eq("RULE_ID", uuid).eq("DEL_FLAG","0"));
            for (SwCkClearRulesLine clearRulesLine : rulesLinesDeatails) {
                if (!updateIds.contains(clearRulesLine.getId())) {
                    rulesLinesRemoveList.add(clearRulesLine);
                }
            }
            //移除本次删除的数据
            if (CollectionUtil.isNotEmpty(rulesLinesRemoveList)) {
                rulesLinesRemoveList.forEach(x -> x.setDelFlag(CommonConstants.STATUS_DEL));
                swCkClearRulesLineService.updateBatchById(rulesLinesRemoveList);
            }
            //更新本次修改的数据
            if (CollectionUtil.isNotEmpty(updateData)) {
                swCkClearRulesLineService.updateBatchById(updateData);
            }
            //新增本次添加的数据
            if (CollectionUtil.isNotEmpty(insertData)) {
                //复制公共属性
                for (SwCkClearRulesLine detail : insertData) {
                    ObjectUtils.setDefaultFiledValueOfBelongToLine(detail);
                }
                swCkClearRulesLineService.saveBatch(insertData);
            }
        }
        return true;
    }

    @Override
    @Transactional
    public SwCkClearRulesDTO getDetailById(Long id) {
        SwCkClearRulesDTO swCkClearRulesDTO = new SwCkClearRulesDTO();
        SwCkClearRules swCkClearRules = getById(id);
        List<SwCkClearRulesLine> rulesLinesDeatails = swCkClearRulesLineService.list(new QueryWrapper<SwCkClearRulesLine>().eq("RULE_ID", swCkClearRules.getUuid()).eq("DEL_FLAG", "0"));
        swCkClearRulesDTO.setDataDetails(rulesLinesDeatails);
        swCkClearRulesDTO.setDatas(swCkClearRules);
        return swCkClearRulesDTO;
    }

    @Override
    public void export(List<Long> ids, HttpServletResponse response) {
        List<Map<String,String>> lineMap = this.baseMapper.selectLineMap();

        List<SwCkClearRules> list = new ArrayList<>();
        for(Long id : ids){
            SwCkClearRules swCkClearRules = this.getById(id);
            list.add(swCkClearRules);
        }
        List<SwCkClearRulesExcelDTO> records = new ArrayList<>();
        for(SwCkClearRules obj : list){
            SwCkClearRulesExcelDTO dto = new SwCkClearRulesExcelDTO();
            dto.setRuleCycle(obj.getBeginTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))  + "~" + obj.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            dto.setClearRulesName(listClearRules(obj.getClearRules()));
            dto.setSubClearRulesName(SubClearRulesAll(obj.getClearRules(),obj.getSubClearRules()));
            dto.setOperatorsName(getServiceName(obj.getOperators()));
            dto.setCountTicket(obj.getCountTicket());
            dto.setDataSource("1".equals(obj.getDataSource()) ? "系统计算" : "人工添加");
            dto.setUsedState("1".equals(obj.getUsedState()) ? "使用中" : "暂停使用");
            records.add(dto);
        }
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("清分规则管理", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/SwCkClearRulesExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("清分规则管理").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出清分规则管理错误");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
    //清分规则管理-人工协议清分比例计算 ,按日期范围,

    /**
     * 各线路Sum=C1+C2+C3+C4+C5+G4+G5+G6+G7+G9+H2  用来计算比例，线路百分分母是所有运营商各个线路总计
     * C1+C2+C3+C4+C5 + E2 + F2 + G4 + G5 + G6 + G7 + G9 + H2，用此值，
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public Boolean autoComputeDay(String startDate, String endDate) {
        log.info("清分规则管理---人工协议清分系统自动计算开始于:{}", LocalDateTime.now());
        List<String> listServiceOrg = swCkSysCleaningConsTicketService.selectServiceIdList();
        if (listServiceOrg != null && !listServiceOrg.isEmpty()) {

            PigxUser user = SecurityUtils.getUser();
            //存放临时变量到内存中，减少SQL查询
            Map<String,BigDecimal> mapServiceI = new HashMap<>();//单个运营商的I值
            Map<String,BigDecimal> mapI = new HashMap<>();//单个线路的I值

            BigDecimal sumI = new BigDecimal("0"); //所有运营商I值
            Map<String,List<String>> mapListLine= new HashMap<>(); //存储运营商下的线路编号

		    List<Map<String,Object>> listSystemClearData = swCkSysCleaningConsTicketService.getE2F2(startDate,endDate);

            //计算合计值
            for (String serviceOrg : listServiceOrg) {
                List<String> listLine = swCkSysCleaningConsTicketService.selectLineListByService(startDate,endDate,serviceOrg);
                mapListLine.put(serviceOrg,listLine);


                if (listLine != null && !listLine.isEmpty()) {
                    BigDecimal sumServiceI = new BigDecimal("0");
                    for (String lineCode : listLine) {
                        //各指标定义,参见word文档,下同
                        BigDecimal C1 = swCkSysCleaningConsTicketService.getC1(startDate,endDate,lineCode);
                        BigDecimal C2 = swCkSysCleaningConsTicketService.getC2(startDate,endDate,lineCode);
                        BigDecimal C3 = swCkSysCleaningConsTicketService.getC3(startDate,endDate,lineCode);
                        BigDecimal C4 = swCkSysCleaningConsTicketService.getC4(startDate,endDate,lineCode);
                        BigDecimal C5 = swCkSysCleaningConsTicketService.getC5(startDate,endDate,lineCode);
                        //BigDecimal C61 = swCkSysCleaningConsTicketService.getC61(startDate,endDate,lineCode);
                        BigDecimal C6 = C1.add(C2).add(C3).add(C4).add(C5);//.add(C61);

                        BigDecimal E2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"cat");//dailyReportMap.get("E2"); 改为从系统清分获取
                        BigDecimal F2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"traffic");//dailyReportMap.get("F2");改为从系统清分获取
						/*

                        Map<String,Long> dailyReportMap = swCkSysCleaningConsTicketService.getDailyReportMap(startDate,endDate,lineCode,serviceOrg);
                        Long E2 = dailyReportMap.get("E2");
                        Long F2 = dailyReportMap.get("F2");
                        if(SwCkClearRuleConstans.SERVICE_ID_XAZT.equals(serviceOrg)|| SwCkClearRuleConstans.SERVICE_ID_XIXIAN.equals(serviceOrg)){  //西安地铁的单独获取长安通刷卡消费和交通一卡通总计，其他线路是否有此需求待定
                            Map<String,Long> subwayCatMap = swCkSysCleaningConsTicketService.getXasubwayCatTicketPayCardAndTrafficCardMap(startDate,endDate,lineCode);
                            E2 = subwayCatMap.get("E2");
                            F2 = subwayCatMap.get("F2");
                        }*/

                        BigDecimal G4 = swCkSysCleaningConsTicketService.getG4(startDate,endDate,lineCode);
                        BigDecimal G5 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG5(startDate,endDate,lineCode);
                        BigDecimal G6 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG6(startDate,endDate,lineCode);
                        BigDecimal G7 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG7(startDate,endDate,lineCode);
                        BigDecimal G9 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG9(startDate,endDate,lineCode);
                        BigDecimal H2 = swCkSysCleaningConsTicketService.getH2(startDate,endDate,lineCode);
                        BigDecimal I = C6.add(E2).add(F2).add(G4).add(G5).add(G6).add(G7).add(G9).add(H2);;

                        sumI = sumI.add(I);
                        sumServiceI = sumServiceI.add(I);
                        mapI.put(serviceOrg+","+lineCode, I);

                    }
                    mapServiceI.put(serviceOrg, sumServiceI);
                }

            }//for 循环运营商结束

            //插入数据库
            List<SwCkClearRules> listSwCkClearRules = new ArrayList<>();//存放所有主表数据
            List<SwCkClearRulesLine> listSwCkClearRulesLine = new ArrayList<>(); //存放所有子表数据
            List<SwCkClearRules> listSwCkClearOldRules =new ArrayList<>(); //存放所有主表需要设置为禁用状态的值

            for (String serviceOrg : listServiceOrg) {
                BigDecimal serviceSumI = mapServiceI.get(serviceOrg);//该运营商下的所有线路金额
                List<String> listLine = mapListLine.get(serviceOrg);
                String uuid = UUID.randomUUID().toString().toLowerCase();
                //组织主表数据
                SwCkClearRules insertSwCkClearRules = new SwCkClearRules();
                insertSwCkClearRules.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                insertSwCkClearRules.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                insertSwCkClearRules.setClearRules(SwCkClearRuleConstans.CLEAR_RULE_MANMADE);
                insertSwCkClearRules.setOperators(serviceOrg);
				insertSwCkClearRules.setSubClearRules("1");//无 20210812
                insertSwCkClearRules.setDelFlag("0");

                QueryWrapper<SwCkClearRules> query = Wrappers.query(insertSwCkClearRules);
                List<SwCkClearRules> list = this.list(query);
                //TODO 需要增加验证，如果以前存在过规则，将原来的设置为禁用
                if(CollectionUtil.isNotEmpty(list)){
                    list.forEach(x -> x.setUsedState("2"));
                }
                listSwCkClearOldRules.addAll(list);

                //系统计算
                insertSwCkClearRules.setDataSource("1");
                //人工协议清分比例（与其他运营商）
                String J1 = "0.00";
                if (sumI.doubleValue()!= 0){
                    J1 = String.valueOf((serviceSumI.doubleValue()) / (sumI.doubleValue()) * 100);
                }
                insertSwCkClearRules.setCountTicket(J1);//清分比例
                insertSwCkClearRules.setUsedState("1"); //暂停使用  1.使用中  2.暂停使用
                insertSwCkClearRules.setDeptId(user.getDeptId());
                insertSwCkClearRules.setCreatorId(user.getId());
                insertSwCkClearRules.setCreatorName(user.getNikeName());
                insertSwCkClearRules.setUuid(uuid);
                listSwCkClearRules.add(insertSwCkClearRules);

                //组织
                if (listLine != null && !listLine.isEmpty()) {
                    for (String lineCode : listLine) {
                        BigDecimal I = mapI.get(serviceOrg+","+lineCode); //线路金额
                        String lineJ1 = "0.00";
                        if(serviceSumI.doubleValue()!= 0) {
                            //lineJ1 = String.format("%.2f", (((I.doubleValue()) / (serviceSumI.doubleValue())) * 100));
                            lineJ1 = String.valueOf((I.doubleValue()) / (sumI.doubleValue()) * 100);

                        }

                        SwCkClearRulesLine insertSwCkClearRulesLine = new SwCkClearRulesLine();

                        insertSwCkClearRulesLine.setLineCode(lineCode);
                        insertSwCkClearRulesLine.setCountTicket(lineJ1);//人工协议清分比例（与其他运营商）
                        insertSwCkClearRulesLine.setRuleId(insertSwCkClearRules.getUuid());
                        insertSwCkClearRulesLine.setDeptId(user.getDeptId());
                        insertSwCkClearRulesLine.setCreatorId(user.getId());
                        insertSwCkClearRulesLine.setCreatorName(user.getNikeName());

                        listSwCkClearRulesLine.add(insertSwCkClearRulesLine);
                    }

                }
            }
            boolean isOk1 = false;
            boolean isOk2 = false;
            if(CollectionUtil.isNotEmpty(listSwCkClearRules)){
                isOk1 = this.saveBatch(listSwCkClearRules);
            }
            //如果存在改为禁用
            if(CollectionUtil.isNotEmpty(listSwCkClearOldRules)){
                this.updateBatchById(listSwCkClearOldRules);
            }
            if(CollectionUtil.isNotEmpty(listSwCkClearRulesLine)){
                isOk2 = swCkClearRulesLineService.saveBatch(listSwCkClearRulesLine);
            }
            return isOk1 || isOk2; //如果不保存子表就不会返回true
        }

        return false;

    }


    /**
     * 按月清分，包括应急纸票大客流、故障退票，纪念票、日票规则，
     *   注明：对于应急纸票误出站、正常退票两项初始化时默认是100%，库表默认加上，以后每次不需要重新生成。
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public Boolean autoComputeMonth(String startDate,String endDate){
    	 //获取所有运营商
   	    List<String> listServiceOrg = swCkSysCleaningConsTicketService.selectServiceIdList();
   	    if (listServiceOrg != null && !listServiceOrg.isEmpty()) {   	    	
   	        //PigxUser user = SecurityUtils.getUser();
   	        List<SwCkClearRules> listSwCkClearRules = new ArrayList<>();//存放所有主表数据     	
            List<SwCkClearRulesLine> listSwCkClearRulesLine = new ArrayList<>(); //存放所有子表数据
            List<SwCkClearRules> listSwCkClearOldRules =new ArrayList<>(); //存放所有主表需要设置为禁用状态的值
   	        
            //1.应急纸票大客流，需要找到每个运营商的I值，然后根据组合的运营商数量，组织分母对应运营商的金额合计。分子为各自运营商。
   	        //2.故障退款， 西安地铁-机场（西安地铁-西安中铁） 算出两个运营商的系统清分金额合计（A，B），进而算出两个运营商的人工协议清分比例（A/（A+B），B/（A+B）），‘
   	        //           如果A>B,则两个运营商的特殊情况退票的清分比例都为 A/（A+B），否则都为B/（A+B）
   	        //3.纪念票、日票按清分接口的单个运营商清分次数/所有运营商的清分金额合计,此部分需要合并到这里。
            
            //-----1.1.1纪念票和日票先查询部分数据 开始-------
            List<Map<String,Object>> lstDailyAll = swCkSysCleaningConsTicketService.getAccDailySpecialTicketMap(startDate, endDate);//日票的各个线路的金额
            List<Map<String,Object>> lstSunivenirAll = swCkSysCleaningConsTicketService.getAccSouvenirSpecialTicketMap(startDate, endDate);//纪念票的各个线路的金额           
     	    BigDecimal lDailyAll = new BigDecimal("0");
     	    BigDecimal lSunivenirAll = new BigDecimal("0");
     	    if(lstDailyAll!=null && !lstDailyAll.isEmpty()){
     	    	 //TODO stream 遍历赋值，取所有运营商的金额的合计,按清分次数来算比例，金额只是显示
         		lDailyAll = lstDailyAll.stream().map(m -> new BigDecimal(String.valueOf(m.get("cleanNumber")))).reduce(BigDecimal.ZERO,BigDecimal::add);
     	    }
     	    if(lstSunivenirAll!=null && !lstSunivenirAll.isEmpty()){
                //TODO stream 遍历赋值，取所有运营商的金额的合计
     		    lSunivenirAll = lstSunivenirAll.stream().map(m -> new BigDecimal(String.valueOf(m.get("cleanNumber")))).reduce(BigDecimal.ZERO,BigDecimal::add);
     	    }
     	   //-----1.1.1纪念票和日票先查询部分数据 结束-------
            
            
            Map<String,BigDecimal> mapServiceI = new HashMap<>();//单个运营商的I值
            Map<String,BigDecimal> mapI = new HashMap<>();//单个线路的I值
            BigDecimal sumI = new BigDecimal("0"); //所有运营商I值
 		    Map<String,List<String>> mapListLine= new HashMap<>(); //存储运营商下的线路编号
			
			//长安通和交通卡系统清分数据
			List<Map<String,Object>> listSystemClearData = swCkSysCleaningConsTicketService.getE2F2(startDate,endDate);
            
			//1. 循环遍历运营商，组织I的值
 		    for (String serviceOrg : listServiceOrg) {
              	   List<String> listLine = swCkSysCleaningConsTicketService.selectLineListByService(startDate,endDate,serviceOrg);
              	   mapListLine.put(serviceOrg, listLine);
              	   if (listLine != null && !listLine.isEmpty()) {
                       BigDecimal sumServiceI = new BigDecimal("0");
                       for (String lineCode : listLine) {						
                           //各指标定义,参见word文档,下同
                           BigDecimal C1 = swCkSysCleaningConsTicketService.getC1(startDate,endDate,lineCode);
                           BigDecimal C2 = swCkSysCleaningConsTicketService.getC2(startDate,endDate,lineCode);
                           BigDecimal C3 = swCkSysCleaningConsTicketService.getC3(startDate,endDate,lineCode);
                           BigDecimal C4 = swCkSysCleaningConsTicketService.getC4(startDate,endDate,lineCode);
                           BigDecimal C5 = swCkSysCleaningConsTicketService.getC5(startDate,endDate,lineCode);
						   //BigDecimal C61 = swCkSysCleaningConsTicketService.getC61(startDate,endDate,lineCode);
                           BigDecimal C6 = C1.add(C2).add(C3).add(C4).add(C5);//.add(C61);

						   BigDecimal E2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"cat");//dailyReportMap.get("E2"); 改为从系统清分获取
                           BigDecimal F2 = getSystemClearLongValueByLineCode(listSystemClearData,lineCode,"traffic");//dailyReportMap.get("F2");改为从系统清分获取
                           
						   /*
						   Map<String,Object> dailyReportMap = swCkSysCleaningConsTicketService.getDailyReportMap(startDate,endDate,lineCode,serviceOrg);
                           BigDecimal E2 = new BigDecimal(String.valueOf(dailyReportMap.get("E2")));
                           BigDecimal F2 = new BigDecimal(String.valueOf(dailyReportMap.get("F2")));
                           if(SwCkClearRuleConstans.SERVICE_ID_XAZT.equals(serviceOrg)|| SwCkClearRuleConstans.SERVICE_ID_XIXIAN.equals(serviceOrg)){  //西安地铁的单独获取长安通刷卡消费和交通一卡通总计，其他线路是否有此需求待定
                                Map<String,BigDecimal> subwayCatMap = swCkSysCleaningConsTicketService.getXasubwayCatTicketPayCardAndTrafficCardMap(startDate,endDate,lineCode);
                                E2 = subwayCatMap.get("E2");
                                F2 = subwayCatMap.get("F2");
                            }
							*/

                           BigDecimal G4 = swCkSysCleaningConsTicketService.getG4(startDate,endDate,lineCode);
                           BigDecimal G5 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG5(startDate,endDate,lineCode);
                           BigDecimal G6 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG6(startDate,endDate,lineCode);
                           BigDecimal G7 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG7(startDate,endDate,lineCode);
                           BigDecimal G9 = new BigDecimal("0");//swCkSysCleaningConsTicketService.getG9(startDate,endDate,lineCode);
                           BigDecimal H2 = swCkSysCleaningConsTicketService.getH2(startDate,endDate,lineCode);
                           BigDecimal I = C6.add(E2).add(F2).add(G4).add(G5).add(G6).add(G7).add(G9).add(H2);;

                           sumI = sumI.add(I);
                           sumServiceI = sumServiceI.add(I);
    					   mapI.put(serviceOrg+","+lineCode, I);
                           
                       }
                       mapServiceI.put(serviceOrg, sumServiceI);
                   }             	   
                    
     		   }//for循环运营商，组织各自的I值结束
 		        
 		        //初始化主表的ID
                Map<String,String> mainUUIDs = new HashMap<>();
 			   initMainUUids(mainUUIDs);  
 			   //2.1组织大客流的主表数据
 	 		   calculateMainRulesByMonth(SwCkClearRuleConstans.CLEAR_RULE_EMERGENCY_BIGSTREAM, mapServiceI,sumI,listSwCkClearRules,listSwCkClearOldRules,mainUUIDs,startDate, endDate);
 	 		   //2.2.组织故障退款的主表数据
 	 		   calculateMainRulesByMonth(SwCkClearRuleConstans.CLEAR_RULE_RETURN_ERROR, mapServiceI,sumI,listSwCkClearRules,listSwCkClearOldRules,mainUUIDs,startDate, endDate);
			   //2.3.组织正常退票的主表数据，此规则不需要设置到线路级
 	 		   calculateMainRulesByMonth(SwCkClearRuleConstans.CLEAR_RULE_RETURN_NORMAL, mapServiceI,sumI,listSwCkClearRules,listSwCkClearOldRules,mainUUIDs,startDate, endDate);
 	 		   
 	 		   //3.组织子表数据

 	 		 for (String serviceOrg : listServiceOrg) {
            	   List<String> listLine =  mapListLine.get(serviceOrg);
            	   for (String lineCode : listLine) {
                       BigDecimal lineI = mapI.get(serviceOrg+","+lineCode);
                       //3.1 组织大客流和故障退款子表数据
                 	  calculateSubRulesByMonth(serviceOrg,lineCode,mapServiceI,lineI,listSwCkClearRulesLine,mainUUIDs);
                   } 
            	   //--------------------------组织日票和纪念票-----------------开始
            	   /*
        		    * lstDailyAll中用stream获取当前运营商下的对应的线路listLine 合计金额赋值到变量lDailyOrg
        		    * Long lDailyOrg =0L;  //取对应运营商的对应金额的合计
        		    * */
                   List<Map<String, Object>> lstDailyAllCurrent = lstDailyAll.stream().filter(item ->
                           new ArrayList<>(listLine).contains(String.valueOf(item.get("lineCode")))
                   ).collect(Collectors.toList());
                   BigDecimal lDailyOrg = lstDailyAllCurrent.stream().map(m -> new BigDecimal(String.valueOf(m.get("cleanNumber")))).reduce(BigDecimal.ZERO,BigDecimal::add);

                   //分别处理（日票）清分比例
                   calculationRules(startDate,endDate,listSwCkClearRules,listSwCkClearOldRules,
                           listSwCkClearRulesLine,serviceOrg,listLine,
                           lDailyAll,lstDailyAllCurrent,lDailyOrg,SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET);


              
                   List<Map<String, Object>> lstSunivenirAllCurrent = lstSunivenirAll.stream().filter(item ->
                           new ArrayList<>(listLine).contains(String.valueOf(item.get("lineCode")))
                   ).collect(Collectors.toList());
                   BigDecimal lstSunivenirOrg = lstSunivenirAllCurrent.stream().map(m -> new BigDecimal(String.valueOf(m.get("cleanNumber")))).reduce(BigDecimal.ZERO,BigDecimal::add);

                   //分别处理（纪念票）清分比例
                   calculationRules(startDate,endDate,listSwCkClearRules,listSwCkClearOldRules,
                           listSwCkClearRulesLine,serviceOrg,listLine,
                           lSunivenirAll,lstSunivenirAllCurrent,lstSunivenirOrg, SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET);
                   //--------------组织日票和纪念票-----------------结束

            	   
              } 	 		 
 	 	   	        
 	 		 boolean isOk1 = false;
 	         boolean isOk2 = false;
 	         if(listSwCkClearRules!=null && !listSwCkClearRules.isEmpty()){
 	        	   isOk1 = this.saveBatch(listSwCkClearRules);
 	         }
 	         //如果存在改为禁用
 	         if(CollectionUtil.isNotEmpty(listSwCkClearOldRules)){
 	               this.updateBatchById(listSwCkClearOldRules);
 	         }
 	         if (listSwCkClearRulesLine !=null && !listSwCkClearRulesLine.isEmpty()){
 	        	   isOk2 = swCkClearRulesLineService.saveBatch(listSwCkClearRulesLine);
 	         }
 	         return isOk1 || isOk2; //如果不保存子表就不会返回true
 	 		   
   	    }    
   	    return false;
    	
    }
	private void initMainUUids(Map<String,String> mainUUIDs){
    	    String UUID_BIGSTREAM_XADT_XIXIAN_XADT = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_XADT";
			String UUID_BIGSTREAM_XADT_XIXIAN_XIXIAN = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_XIXIAN";
			
			String UUID_BIGSTREAM_XADT_AIR_XADT = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_AIR_XADT";
			String UUID_BIGSTREAM_XADT_AIR_AIR = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_AIR_AIR";
			
			String UUID_BIGSTREAM_XADT_XIXIAN_AIR_XADT = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_AIR_XADT";
			String UUID_BIGSTREAM_XADT_XIXIAN_AIR_XIXIAN = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_AIR_XIXIAN";
			String UUID_BIGSTREAM_XADT_XIXIAN_AIR_AIR = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_AIR_AIR";
			
			String UUID_BIGSTREAM_XADT_XAZT_XADT= UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XAZT_XADT";
			String UUID_BIGSTREAM_XADT_XAZT_XAZT = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XAZT_XAZT";
			
			String UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XADT = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_XAZT_XADT";
			String UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XIXIAN = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_XAZT_XIXIAN";
			String UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XAZT = UUID.randomUUID().toString().toLowerCase();//"BIGSTREAM_XADT_XIXIAN_XAZT_XAZT";
			
			String UUID_RETURN_ERROR_XADT_AIR_XADT =UUID.randomUUID().toString().toLowerCase();//"RETURN_ERROR_XADT_AIR_XADT";
			String UUID_RETURN_ERROR_XADT_AIR_AIR =UUID.randomUUID().toString().toLowerCase();//"RETURN_ERROR_XADT_AIR_AIR";
			
			String UUID_RETURN_ERROR_XADT_XAZT_XADT =UUID.randomUUID().toString().toLowerCase();//"RETURN_ERROR_XADT_XAZT_XADT";
			String UUID_RETURN_ERROR_XADT_XAZT_XAZT =UUID.randomUUID().toString().toLowerCase();//"RETURN_ERROR_XADT_XAZT_XAZT";

			String UUID_RETURN_NORMAL_XADT_AIR_XADT =UUID.randomUUID().toString().toLowerCase();//"RETURN_NORMAL_XADT_AIR_XADT";
			String UUID_RETURN_NORMAL_XADT_AIR_AIR =UUID.randomUUID().toString().toLowerCase();//"RETURN__NORMAL_XADT_AIR_AIR";
			
			String UUID_RETURN_NORMAL_XADT_XAZT_XADT =UUID.randomUUID().toString().toLowerCase();//"RETURN__NORMAL_XADT_XAZT_XADT";
			String UUID_RETURN_NORMAL_XADT_XAZT_XAZT =UUID.randomUUID().toString().toLowerCase();//"RETURN__NORMAL_XADT_XAZT_XAZT";
		    
			mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XADT, UUID_BIGSTREAM_XADT_XIXIAN_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XIXIAN, UUID_BIGSTREAM_XADT_XIXIAN_XIXIAN);
		    
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_AIR_XADT, UUID_BIGSTREAM_XADT_AIR_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_AIR_AIR, UUID_BIGSTREAM_XADT_AIR_AIR);
		    
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_XADT, UUID_BIGSTREAM_XADT_XIXIAN_AIR_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_XIXIAN, UUID_BIGSTREAM_XADT_XIXIAN_AIR_XIXIAN);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_AIR, UUID_BIGSTREAM_XADT_XIXIAN_AIR_AIR);
		    
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XAZT_XADT, UUID_BIGSTREAM_XADT_XAZT_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XAZT_XAZT, UUID_BIGSTREAM_XADT_XAZT_XAZT);
		    
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XADT, UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XIXIAN, UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XIXIAN);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XAZT, UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XAZT);
		    
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_AIR_XADT, UUID_RETURN_ERROR_XADT_AIR_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_AIR_AIR, UUID_RETURN_ERROR_XADT_AIR_AIR);
		    
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_XAZT_XADT, UUID_RETURN_ERROR_XADT_XAZT_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_XAZT_XAZT, UUID_RETURN_ERROR_XADT_XAZT_XAZT);

			mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_AIR_XADT, UUID_RETURN_NORMAL_XADT_AIR_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_AIR_AIR, UUID_RETURN_NORMAL_XADT_AIR_AIR);
		    
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_XAZT_XADT, UUID_RETURN_NORMAL_XADT_XAZT_XADT);
		    mainUUIDs.put(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_XAZT_XAZT, UUID_RETURN_NORMAL_XADT_XAZT_XAZT);
    }
    
	private void calculateMainRulesByMonth(String clearRule, Map<String, BigDecimal> mapServiceI, BigDecimal allI, List<SwCkClearRules> listSwCkClearRules, List<SwCkClearRules> listSwCkClearOldRules, Map<String, String> mainUUIDs, String beginDate, String endDate){
    	Map<String,String> mainRulesParam = new HashMap();
    	mainRulesParam.put("beginDate", beginDate);
    	mainRulesParam.put("endDate", endDate);    	
    	mainRulesParam.put("clearRules", clearRule);

        BigDecimal  lXzdtAndXixan = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN));
        BigDecimal  lXadtAndAir =  mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR));
        BigDecimal  lXadtAndXixianAndAir =  mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR));
        BigDecimal  lXadtAndXazt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT));
        BigDecimal  lXadtAndXixianAndXazt =  mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT));
    	
    
    	//应急纸票大客流
    	if(clearRule.equals(SwCkClearRuleConstans.CLEAR_RULE_EMERGENCY_BIGSTREAM)){
 		   //1. 西安地铁-西咸清分主表ID  1
    	   
    	  //1.1 西安地铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
    	   mainRulesParam.put("clearSubRules", "1");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XADT)); 
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXzdtAndXixan.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixian_xadt = createMainRules(listSwCkClearOldRules,mainRulesParam);
    	   
    	   //1.2 西咸
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XIXIAN);
    	   mainRulesParam.put("clearSubRules", "1");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XIXIAN));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN).doubleValue() / lXzdtAndXixan.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixian_xixian = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //2.  西安地铁-机场
    	   //2.1  西安地铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
    	   mainRulesParam.put("clearSubRules", "2");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_AIR_XADT));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndAir.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtAir_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   //2.2机场
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_AIR);
    	   mainRulesParam.put("clearSubRules", "2");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_AIR_AIR));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR).doubleValue() / lXadtAndAir.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtAir_air = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //3.  西安地铁-西咸-机场 
    	   //3.1  西安地铁 
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
    	   mainRulesParam.put("clearSubRules", "3");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_XADT));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndXixianAndAir.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixianAir_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //3.2 西咸
    	   
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XIXIAN);
    	   mainRulesParam.put("clearSubRules", "3");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_XIXIAN));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN).doubleValue() / lXadtAndXixianAndAir.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixianAir_xixian = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   

    	   //3.3 机场
    	   
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_AIR);
    	   mainRulesParam.put("clearSubRules", "3");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_AIR));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR).doubleValue() / lXadtAndXixianAndAir.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixianAir_air = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //4.西安地铁-西安中铁
    	   //4.1 西安地铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
    	   mainRulesParam.put("clearSubRules", "4");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XAZT_XADT));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndXazt.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXazt_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //4.2 西安中铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XAZT);
    	   mainRulesParam.put("clearSubRules", "4");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XAZT_XAZT));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT).doubleValue() / lXadtAndXazt.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXazt_xazt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //5.西安地铁-西咸-西安中铁
    	   //5.1  西安地铁 
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
    	   mainRulesParam.put("clearSubRules", "5");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XADT));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndXixianAndXazt.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixianXazt_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //5.2 西咸
    	   
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XIXIAN);
    	   mainRulesParam.put("clearSubRules", "5");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XIXIAN));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN).doubleValue() / lXadtAndXixianAndXazt.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixianXazt_xixian = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   

    	   //5.3 西安中铁
    	   
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XAZT);
    	   mainRulesParam.put("clearSubRules", "5");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XAZT));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT).doubleValue() / lXadtAndXixianAndXazt.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXixianXazt_xazt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   /*
			    * TODO  需要根据日期范围，清分规则，清分子类型，运营商 判断是否存在，如果存在
			    * 将原来的状态设置为暂停使用
			    * 
			    * 其他几个同理，都要重新设置
			    * */
            listSwCkClearRules.add(insertRulesXadtXixian_xadt);
            listSwCkClearRules.add(insertRulesXadtXixian_xixian);
            listSwCkClearRules.add(insertRulesXadtAir_xadt);
            listSwCkClearRules.add(insertRulesXadtAir_air);
            listSwCkClearRules.add(insertRulesXadtXixianAir_xadt);
            listSwCkClearRules.add(insertRulesXadtXixianAir_xixian);
            listSwCkClearRules.add(insertRulesXadtXixianAir_air);
            listSwCkClearRules.add(insertRulesXadtXazt_xadt);
            listSwCkClearRules.add(insertRulesXadtXazt_xazt);
            listSwCkClearRules.add(insertRulesXadtXixianXazt_xadt);
            listSwCkClearRules.add(insertRulesXadtXixianXazt_xixian);
            listSwCkClearRules.add(insertRulesXadtXixianXazt_xazt);
    	//故障退款	
    	}else if(clearRule.equals(SwCkClearRuleConstans.CLEAR_RULE_RETURN_ERROR)){
            BigDecimal lXadt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT) ;
            BigDecimal lAir = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR) ;
            BigDecimal lXazt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT) ;
    	  //2.  西安地铁-机场
     	   //2.1  西安地铁
     	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
     	   mainRulesParam.put("clearSubRules", "1");
     	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_AIR_XADT));
     	   
     	   /*2021-11-18 调整为按正常两个运营商计算比例，计算清分时再根据大小计算金额
     	   if(lXadt.compareTo(lAir) == 1){// =1表示a>b ,=-1表示a<b
     		  //算出两个运营商的系统清分金额合计（A，B），进而算出两个运营商的人工协议清分比例（A/（A+B），B/（A+B）），如果A>B,则两个运营商的特殊情况退票的清分比例都为 A/（A+B），否则都为B/（A+B）
     		 mainRulesParam.put("scaleSize",String.valueOf(((lXadt.doubleValue() / lXadtAndAir.doubleValue()) * 100)));
     	   }else{
     		  mainRulesParam.put("scaleSize",String.valueOf(((lAir.doubleValue() / lXadtAndAir.doubleValue()) * 100)));
     	   }*/
     	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndAir.doubleValue()) * 100)));
     	   
     	     	  
     	   SwCkClearRules insertRulesXadtAir_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
     	   //2.2机场
     	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_AIR);
     	   mainRulesParam.put("clearSubRules", "1");
     	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_AIR_AIR));
     	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR).doubleValue() / lXadtAndAir.doubleValue()) * 100)));
     	   //与2.1一样 scaleSize
     	   SwCkClearRules insertRulesXadtAir_air = createMainRules(listSwCkClearOldRules, mainRulesParam);
     	   
     	  //4.西安地铁-西安中铁
    	   //4.1 西安地铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
    	   mainRulesParam.put("clearSubRules", "2");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_XAZT_XADT));
    	   
    	   /*
    	   if(lXadt.compareTo(lXazt) == 1){//=1表示a>b ,=-1表示a<b
      		  //算出两个运营商的系统清分金额合计（A，B），进而算出两个运营商的人工协议清分比例（A/（A+B），B/（A+B）），如果A>B,则两个运营商的特殊情况退票的清分比例都为 A/（A+B），否则都为B/（A+B）
      		 mainRulesParam.put("scaleSize",String.valueOf(((lXadt.doubleValue() / lXadtAndXazt.doubleValue()) * 100)));
      	   }else{
      		  mainRulesParam.put("scaleSize",String.valueOf(((lXazt.doubleValue() / lXadtAndAir.doubleValue()) * 100)));
      	   } */   
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndXazt.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXazt_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //4.2 西安中铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XAZT);
    	   mainRulesParam.put("clearSubRules", "2");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_XAZT_XAZT));
    	   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT).doubleValue() / lXadtAndXazt.doubleValue()) * 100)));
    	   //与4.1一样 scaleSize
    	   SwCkClearRules insertRulesXadtXazt_xazt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   /*
		    * TODO  需要根据日期范围，清分规则，清分子类型，运营商 判断是否存在，如果存在
		    * 将原来的状态设置为暂停使用
		    * 
		    * 其他几个同理，都要重新设置
		    * */	       
	        listSwCkClearRules.add(insertRulesXadtAir_xadt); 
	        listSwCkClearRules.add(insertRulesXadtAir_air); 
	        listSwCkClearRules.add(insertRulesXadtXazt_xadt); 
	        listSwCkClearRules.add(insertRulesXadtXazt_xazt); 
	       
    	//正常退票
    	}else if(clearRule.equals(SwCkClearRuleConstans.CLEAR_RULE_RETURN_NORMAL)){
    	   BigDecimal lXadt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT) ;
    	   BigDecimal lAir = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR) ;
    	   BigDecimal lXazt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT) ;
    	  //2.  西安地铁-机场
     	   //2.1  西安地铁
     	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
     	   mainRulesParam.put("clearSubRules", "1");
     	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_AIR_XADT));
		   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndAir.doubleValue()) * 100)));
     	   SwCkClearRules insertRulesXadtAir_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
     	   //2.2机场
     	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_AIR);
     	   mainRulesParam.put("clearSubRules", "1");
     	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_AIR_AIR));
		   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR).doubleValue() / lXadtAndAir.doubleValue()) * 100)));
     	   //与2.1一样 scaleSize
     	   SwCkClearRules insertRulesXadtAir_air = createMainRules(listSwCkClearOldRules, mainRulesParam);
     	   
     	  //4.西安地铁-西安中铁
    	   //4.1 西安地铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XADT);
    	   mainRulesParam.put("clearSubRules", "2");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_XAZT_XADT));
		   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).doubleValue() / lXadtAndXazt.doubleValue()) * 100)));
    	   SwCkClearRules insertRulesXadtXazt_xadt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   //4.2 西安中铁
    	   mainRulesParam.put("serviceOrg", SwCkClearRuleConstans.SERVICE_ID_XAZT);
    	   mainRulesParam.put("clearSubRules", "2");
    	   mainRulesParam.put("uuid", mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_NORMAL_XADT_XAZT_XAZT));
		   mainRulesParam.put("scaleSize",String.valueOf(((mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT).doubleValue() / lXadtAndXazt.doubleValue()) * 100)));
    	   //与4.1一样 scaleSize
    	   SwCkClearRules insertRulesXadtXazt_xazt = createMainRules(listSwCkClearOldRules, mainRulesParam);
    	   
    	   /*
		    * TODO  需要根据日期范围，清分规则，清分子类型，运营商 判断是否存在，如果存在
		    * 将原来的状态设置为暂停使用
		    * 
		    * 其他几个同理，都要重新设置
		    * */	       
	        listSwCkClearRules.add(insertRulesXadtAir_xadt); 
	        listSwCkClearRules.add(insertRulesXadtAir_air); 
	        listSwCkClearRules.add(insertRulesXadtXazt_xadt); 
	        listSwCkClearRules.add(insertRulesXadtXazt_xazt); 
	       
    	}
    	
    }
  //组织子表数据
    private void calculateSubRulesByMonth(String serviceOrg,String lineCode,Map<String,BigDecimal> mapServiceI,BigDecimal lineI,List<SwCkClearRulesLine> listSwCkClearRulesLine,Map<String,String> mainUUIDs){

        BigDecimal  lXadt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT);
        BigDecimal  lXazt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT);
        BigDecimal  lAir = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR);
        BigDecimal  lXixian = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN);

        BigDecimal  lXadtAndXixan = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN));
        BigDecimal  lXadtAndAir =  mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR));
        BigDecimal  lXadtAndXixianAndAir =  mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_AIR));
        BigDecimal  lXadtAndXazt = mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT));
        BigDecimal  lXadtAndXixianAndXazt =  mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XADT).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)).add(mapServiceI.get(SwCkClearRuleConstans.SERVICE_ID_XAZT));
    	
    	if(serviceOrg.equals(SwCkClearRuleConstans.SERVICE_ID_XADT)){
    		/*西安地铁，1. 需要插入到 大客流中的西安地铁记录中
    	     西安地铁-西咸,线路百分比不需要报告西咸，百分比按西安地铁内部清算
    	     西安地铁-机场
    	     西安地铁-西咸-机场
    	     西安地铁-西铁
    	     西安地铁-西咸-西安中铁
    	   2.故障退票中的
    	                     西安地铁-机场
    	                    西安地铁-西铁*/
    		//String scaleSize = String.format("%.2f", ((lineI.doubleValue() / lXadt.doubleValue()) * 100));
			String scaleSize = String.valueOf(((lineI.doubleValue() / lXadt.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXian  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XADT));
			
			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndAir.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtAir  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_AIR_XADT));
			
			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXixianAndAir.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXianAir  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_XADT));
			
			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXazt.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXazt  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XAZT_XADT));
			
			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXixianAndXazt.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXianXazt  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XADT));
			// 2021-11-18 故障退款，线路清分比例 线路合计比例保证100
			//scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndAir.doubleValue()) * 100));
    		scaleSize = String.valueOf(((lineI.doubleValue() / lXadt.doubleValue()) * 100));
    		SwCkClearRulesLine returnErrorXadtAir  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_AIR_XADT));
			
			//scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXazt.doubleValue()) * 100));
    		scaleSize = String.valueOf(((lineI.doubleValue() / lXadt.doubleValue()) * 100));
    		SwCkClearRulesLine returnErrorXadtXazt  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_XAZT_XADT)); 
    		
    		listSwCkClearRulesLine.add(bigStreamXadtXian);
    		listSwCkClearRulesLine.add(bigStreamXadtAir);
    		listSwCkClearRulesLine.add(bigStreamXadtXianAir);
    		listSwCkClearRulesLine.add(bigStreamXadtXazt);
    		listSwCkClearRulesLine.add(bigStreamXadtXianXazt);
    		listSwCkClearRulesLine.add(returnErrorXadtAir);
    		listSwCkClearRulesLine.add(returnErrorXadtXazt);
    		
    	}else if(serviceOrg.equals(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)){
    		 /*西安地铁，1. 需要插入到 大客流中的西安地铁记录中
 	       西安地铁-西咸               	      
 	       西安地铁-西咸-机场		               	       
 	       西安地铁-西咸-西安中铁*/
    		String scaleSize = "0";//String.valueOf(((lineI.doubleValue() / lXadtAndXixan.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXian  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XIXIAN));  
			
			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXixianAndAir.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXianAir  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_XIXIAN));  
			
			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXixianAndXazt.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXianXazt  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XIXIAN));

        	listSwCkClearRulesLine.add(bigStreamXadtXian);
        	listSwCkClearRulesLine.add(bigStreamXadtXianAir);
            listSwCkClearRulesLine.add(bigStreamXadtXianXazt);
    		
    	}else if(serviceOrg.equals(SwCkClearRuleConstans.SERVICE_ID_AIR)){
    		 /*西安地铁，1. 需要插入到 大客流中的西安地铁记录中	               	    
    	     西安地铁-机场
    	     西安地铁-西咸-机场                 	      
    	     2.故障退票中的
    	                     西安地铁-机场         */
    		String scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndAir.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtAir  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_AIR_AIR));

			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXixianAndAir.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXianAir  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_AIR_AIR)); 
			
			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndAir.doubleValue()) * 100));
    		SwCkClearRulesLine returnErrorXadtAir  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_AIR_AIR)); 
			
    		listSwCkClearRulesLine.add(bigStreamXadtAir);
    		listSwCkClearRulesLine.add(bigStreamXadtXianAir); 
    		listSwCkClearRulesLine.add(returnErrorXadtAir);
    		
    	}else if(serviceOrg.equals(SwCkClearRuleConstans.SERVICE_ID_XAZT)){
    		 /*西安地铁，1. 需要插入到 大客流中的西安地铁记录中	               	    
                            西安地铁-西铁   
							西安地铁-西咸-西安中铁
                 2.故障退票中的                 	                      
                                       西安地铁-西铁       */
    		String scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXazt.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXazt  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XAZT_XAZT));  

			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXixianAndXazt.doubleValue()) * 100));
    		SwCkClearRulesLine bigStreamXadtXianXazt  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_BIGSTREAM_XADT_XIXIAN_XAZT_XAZT)); 

			scaleSize = String.valueOf(((lineI.doubleValue() / lXadtAndXazt.doubleValue()) * 100));
    		SwCkClearRulesLine returnErrorXadtXazt  = createSubRules(lineCode,scaleSize,mainUUIDs.get(SwCkClearRuleConstans.UUID_RETURN_ERROR_XADT_XAZT_XAZT)); 
    	    listSwCkClearRulesLine.add(bigStreamXadtXazt);
			listSwCkClearRulesLine.add(bigStreamXadtXianXazt);
    		listSwCkClearRulesLine.add(returnErrorXadtXazt);
    	}
    	
    	
    }
	 /*
     * 组织主表数据的共用类
     */
    private SwCkClearRules createMainRules(List<SwCkClearRules> listSwCkClearOldRules, Map<String, String> mapParam){
        String beginDate = mapParam.get("beginDate");
        String endDate= mapParam.get("endDate");
        String clearRules= mapParam.get("clearRules");
        String clearSubRules= mapParam.get("clearSubRules");
        String scaleSize = mapParam.get("scaleSize");
        String uuid=  mapParam.get("uuid");
        String serviceOrg= mapParam.get("serviceOrg");
        PigxUser user = SecurityUtils.getUser();

        SwCkClearRules insertSwCkClearRules= new SwCkClearRules();
        insertSwCkClearRules.setBeginTime(LocalDate.parse(beginDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        insertSwCkClearRules.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        insertSwCkClearRules.setClearRules(clearRules);
        insertSwCkClearRules.setOperators(serviceOrg);//待定--确认存哪个值
        insertSwCkClearRules.setSubClearRules(clearSubRules);  //待定 clearSubRules
        insertSwCkClearRules.setDelFlag("0");

        QueryWrapper<SwCkClearRules> query = Wrappers.query(insertSwCkClearRules);
        List<SwCkClearRules> list = this.list(query);
        //TODO 需要增加验证，如果以前存在过规则，将原来的设置为禁用
        if(CollectionUtil.isNotEmpty(list)){
            list.forEach(x -> x.setUsedState("2"));
            this.updateBatchById(list);
        }

        insertSwCkClearRules.setUuid(uuid);
        insertSwCkClearRules.setDataSource("1");//
        insertSwCkClearRules.setUsedState("1"); //暂停使用  1.使用中  2.暂停使用  todo 需要增加验证，如果以前存在过规则，将原来的设置为禁用
        if(scaleSize.equals("NaN")){
            scaleSize = "0.00";
        }
        insertSwCkClearRules.setCountTicket(scaleSize);// 统一用这个字段,清分比例
        insertSwCkClearRules.setDeptId(user.getDeptId());
        insertSwCkClearRules.setCreatorId(user.getId());
        insertSwCkClearRules.setCreatorName(user.getNikeName());
        return insertSwCkClearRules;
    } 
    /*
     * 组织子表数据的共用类
     */
    private SwCkClearRulesLine createSubRules(String lineCode,String scaleSize,String mainUuid){
       	    PigxUser user = SecurityUtils.getUser();
    	    SwCkClearRulesLine insertSwCkClearRulesLine = new SwCkClearRulesLine();    	    
    	    insertSwCkClearRulesLine.setLineCode(lineCode);
            if(scaleSize.equals("NaN")){
                scaleSize = "0.00";
            }
    	    insertSwCkClearRulesLine.setCountTicket(scaleSize);
    	    insertSwCkClearRulesLine.setRuleId(mainUuid);//主表的UUID
    	    insertSwCkClearRulesLine.setDeptId(user.getDeptId());
    	    insertSwCkClearRulesLine.setCreatorId(user.getId());
    	    insertSwCkClearRulesLine.setCreatorName(user.getNikeName());
    	    return insertSwCkClearRulesLine;    
    	   
    }
   
    /**
     * 分别处理（日票、计次票、纪念票）清分比例
     * @param startDate
     * @param endDate
     * @param listSwCkClearRules
     * @param listSwCkClearOldRules
     * @param listSwCkClearRulesLine
     * @param serviceOrg 对应运营商编号
     * @param listLine 运营商对应线路
     * @param amountAll 所有运营商金额
     * @param CurrentLineAll 当前运营商下的对应的线路
     * @param CurrentOrg 当前运营商的对应金额的合计
     * @param clearRuleTicket 清分规则
     */
    private void calculationRules(String startDate, String endDate,
                                 List<SwCkClearRules> listSwCkClearRules, List<SwCkClearRules> listSwCkClearOldRules,
                                 List<SwCkClearRulesLine> listSwCkClearRulesLine, String serviceOrg, List<String> listLine,
                                 BigDecimal amountAll, List<Map<String, Object>> CurrentLineAll, BigDecimal CurrentOrg, String clearRuleTicket) {
        PigxUser user = SecurityUtils.getUser();
        String uuid = UUID.randomUUID().toString().toLowerCase();//主表ID

        SwCkClearRules insertSwCkClearRules = new SwCkClearRules();
        insertSwCkClearRules.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        insertSwCkClearRules.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        insertSwCkClearRules.setClearRules(clearRuleTicket);
        insertSwCkClearRules.setSubClearRules("1");//子清分规则无，字典值是1
        insertSwCkClearRules.setOperators(serviceOrg);
        insertSwCkClearRules.setDelFlag("0");

        QueryWrapper<SwCkClearRules> query = Wrappers.query(insertSwCkClearRules);
        List<SwCkClearRules> list = this.list(query);
        //TODO 需要增加验证，如果以前存在过规则，将原来的设置为禁用
        if(CollectionUtil.isNotEmpty(list)){
            list.forEach(x -> x.setUsedState("2"));
        }
        listSwCkClearOldRules.addAll(list);

        insertSwCkClearRules.setUuid(uuid);
        insertSwCkClearRules.setDataSource("1");
        insertSwCkClearRules.setUsedState("1"); //暂停使用  1.使用中  2.暂停使用
        String countTicket = String.valueOf(((CurrentOrg.doubleValue() / amountAll.doubleValue()) * 100));
        if(countTicket.equals("NaN")){
            countTicket = "0.00";
        }
        insertSwCkClearRules.setCountTicket(countTicket);
        insertSwCkClearRules.setDeptId(user.getDeptId());
        insertSwCkClearRules.setCreatorId(user.getId());
        insertSwCkClearRules.setCreatorName(user.getNikeName());
        listSwCkClearRules.add(insertSwCkClearRules);


        if (listLine != null && !listLine.isEmpty()) {
           // if(serviceOrg.equals(SwCkClearRuleConstans.SERVICE_ID_XAZT) || serviceOrg.equals(SwCkClearRuleConstans.SERVICE_ID_XIXIAN)){
                for (String lineCode : listLine) {
                    /*
                     * lstDailyAll中用stream获取当前lineCode的金额赋值到变量lDailyLine  当前线路/该运营商下所有线路合计值
                     * Long lDailyLine =0L;//取当前线路的金额
                     * */
                    BigDecimal CurrentLine = CurrentLineAll.stream()
                            .filter(item -> lineCode.equals(String.valueOf(item.get("lineCode")))).collect(Collectors.toList())
                            .stream().map(m -> new BigDecimal(String.valueOf(m.get("cleanNumber")))).reduce(BigDecimal.ZERO,BigDecimal::add);
                    SwCkClearRulesLine insertSwCkClearRulesLine = new SwCkClearRulesLine();

                    insertSwCkClearRulesLine.setLineCode(lineCode);
					 //清分比例是线路除以所有运营商的金额，不是线路与对应运营商内的比例关系,就是系统内全部线路内划分比例
                    String subCountTicket = String.valueOf(((CurrentLine.doubleValue() / amountAll.doubleValue()) * 100));
                    if(subCountTicket.equals("NaN")){
                        subCountTicket = "0.00";
                    }
                    insertSwCkClearRulesLine.setCountTicket(subCountTicket);
                    insertSwCkClearRulesLine.setRuleId(insertSwCkClearRules.getUuid());//主表的UUID
                    insertSwCkClearRulesLine.setDeptId(user.getDeptId());
                    insertSwCkClearRulesLine.setCreatorId(user.getId());
                    insertSwCkClearRulesLine.setCreatorName(user.getNikeName());
                    listSwCkClearRulesLine.add(insertSwCkClearRulesLine);

                }
            //}

        }
    }


    //自动按月计算特殊票种（日票、计次票、纪念票）清分比例
  
    public Boolean autoComputeSpecialTicketsMonth_OLD(String startDate, String endDate,List<String> clearRules){
    	boolean isContainsDaily = clearRules.contains(SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET);
    	boolean isContainsSouvenir = clearRules.contains(SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET);
    	boolean isContainsCounting = clearRules.contains(SwCkClearRuleConstans.CLEAR_RULE_COUNTING_TICKET);
    	log.info("清分规则管理---系统自动计算开始于:{}", LocalDateTime.now());
        //获取所有运营商
   	    List<String> listServiceOrg = swCkSysCleaningConsTicketService.selectServiceIdList();

       if (listServiceOrg != null && !listServiceOrg.isEmpty()) {

    	   Map<String,List<String>> mapListLine = new HashMap<>(); //存储运营商下的线路编号
           List<Map<String,Object>> lstDailyAll = new ArrayList<>();//日票的各个线路的金额
           List<Map<String,Object>> lstSunivenirAll = new ArrayList<>();//纪念票的各个线路的金额
           List<Map<String,Object>> lstCountingAll = new ArrayList<>();//计次票的各个线路的金额
           // 下面三个值，需要用stream求lstDailyAll、isContainsSouvenir、isContainsCounting中所有金额合计
    	   BigDecimal lDailyAll = new BigDecimal("0");
    	   BigDecimal lSunivenirAll = new BigDecimal("0");
    	   BigDecimal lCountingAll = new BigDecimal("0");

    	   if(isContainsDaily){
    		   lstDailyAll = swCkSysCleaningConsTicketService.getAccDailySpecialTicketMap(startDate, endDate);
               //TODO stream 遍历赋值，取所有运营商的金额的合计
    		   lDailyAll = lstDailyAll.stream().map(m -> new BigDecimal(String.valueOf(m.get("money")))).reduce(BigDecimal.ZERO,BigDecimal::add);
    	   }
    	   if(isContainsSouvenir){
    		   lstSunivenirAll = swCkSysCleaningConsTicketService.getAccSouvenirSpecialTicketMap(startDate, endDate);
               //TODO stream 遍历赋值，取所有运营商的金额的合计
    		   lSunivenirAll = lstSunivenirAll.stream().map(m -> new BigDecimal(String.valueOf(m.get("money")))).reduce(BigDecimal.ZERO,BigDecimal::add);
    	   }
    	   if(isContainsCounting){
    		   lstCountingAll = swCkSysCleaningConsTicketService.getAccCountingSpecialTicketMap(startDate, endDate);
               //TODO stream 遍历赋值，取所有运营商的金额的合计
    		   lCountingAll = lstCountingAll.stream().map(m -> new BigDecimal(String.valueOf(m.get("money")))).reduce(BigDecimal.ZERO,BigDecimal::add);
    	   }
    	   
    	   //计算合计值
    	   List<SwCkClearRules> listSwCkClearRules = new ArrayList<>();//存放所有主表数据
    	   List<SwCkClearRules> listSwCkClearOldRules = new ArrayList<>();//以前存在过规则，将原来的设置为禁用

           List<SwCkClearRulesLine> listSwCkClearRulesLine = new ArrayList<>(); //存放所有子表数据
           for (String serviceOrg : listServiceOrg) {
               List<String> listLine = swCkSysCleaningConsTicketService.selectLineListByService(startDate,endDate,serviceOrg);

               if(isContainsDaily){//日票

        		   /*
        		    * lstDailyAll中用stream获取当前运营商下的对应的线路listLine 合计金额赋值到变量lDailyOrg
        		    * Long lDailyOrg =0L;  //取对应运营商的对应金额的合计
        		    * */
                   List<Map<String, Object>> lstDailyAllCurrent = lstDailyAll.stream().filter(item ->
                           new ArrayList<>(listLine).contains(String.valueOf(item.get("lineCode")))
                   ).collect(Collectors.toList());
                   BigDecimal lDailyOrg = lstDailyAllCurrent.stream().map(m -> new BigDecimal(String.valueOf(m.get("money")))).reduce(BigDecimal.ZERO,BigDecimal::add);

                   //分别处理（日票、计次票、纪念票）清分比例
                   calculationRules(startDate,endDate,listSwCkClearRules,listSwCkClearOldRules,
                           listSwCkClearRulesLine,serviceOrg,listLine,
                           lDailyAll,lstDailyAllCurrent,lDailyOrg,SwCkClearRuleConstans.CLEAR_RULE_DAILY_TICKET);


               }
        	   if(isContainsSouvenir){//纪念票

                   List<Map<String, Object>> lstSunivenirAllCurrent = lstSunivenirAll.stream().filter(item ->
                           new ArrayList<>(listLine).contains(String.valueOf(item.get("lineCode")))
                   ).collect(Collectors.toList());
                   BigDecimal lstSunivenirOrg = lstSunivenirAllCurrent.stream().map(m -> new BigDecimal(String.valueOf(m.get("money")))).reduce(BigDecimal.ZERO,BigDecimal::add);

                   //分别处理（日票、计次票、纪念票）清分比例
                   calculationRules(startDate,endDate,listSwCkClearRules,listSwCkClearOldRules,
                           listSwCkClearRulesLine,serviceOrg,listLine,
                           lSunivenirAll,lstSunivenirAllCurrent,lstSunivenirOrg, SwCkClearRuleConstans.CLEAR_RULE_SOUVENIR_TICKET);

               }
        	   if(isContainsCounting){//计次票

                   List<Map<String, Object>> lstCountingCurrent = lstCountingAll.stream().filter(item ->
                           new ArrayList<>(listLine).contains(String.valueOf(item.get("lineCode")))
                   ).collect(Collectors.toList());
                   BigDecimal lstCountingOrg = lstCountingCurrent.stream().map(m -> new BigDecimal(String.valueOf(m.get("money")))).reduce(BigDecimal.ZERO,BigDecimal::add);

                   //分别处理（日票、计次票、纪念票）清分比例
                   calculationRules(startDate,endDate,listSwCkClearRules,listSwCkClearOldRules,
                           listSwCkClearRulesLine,serviceOrg,listLine,
                           lCountingAll,lstCountingCurrent,lstCountingOrg, SwCkClearRuleConstans.CLEAR_RULE_COUNTING_TICKET);

        	   } 
           }
           boolean isOk1 = false;
           boolean isOk2 = false;
           if(listSwCkClearRules!=null && !listSwCkClearRules.isEmpty()){
        	   isOk1 = this.saveBatch(listSwCkClearRules);
           }
           //如果存在改为禁用
           if(CollectionUtil.isNotEmpty(listSwCkClearOldRules)){
               this.updateBatchById(listSwCkClearOldRules);
           }
           if (listSwCkClearRulesLine !=null && !listSwCkClearRulesLine.isEmpty()){
        	   isOk2 = swCkClearRulesLineService.saveBatch(listSwCkClearRulesLine);
           }
           return isOk1 || isOk2; //如果不保存子表就不会返回true
			
       }
    	
    	
    	return false;
    }

    /**
     * 查询返回数据
     * @return
     */
    @Override
    public List<SwCkClearRulesDTO> selectRules() {
        List<SwCkClearRulesDTO> list = new ArrayList<>();
        //todo 如果传参，里边加上条件就行
        List<SwCkClearRules> swCkClearRulesList = this.list(Wrappers.<SwCkClearRules>lambdaQuery()
                .eq(SwCkClearRules::getUsedState,"1")
                .eq(SwCkClearRules::getDelFlag,"0"));
        for (SwCkClearRules swCkClearRules : swCkClearRulesList) {
            //根据UUid关联查询
            List<SwCkClearRulesLine> listLine = swCkClearRulesLineService.list(Wrappers.<SwCkClearRulesLine>lambdaQuery()
                    .eq(SwCkClearRulesLine::getRuleId,swCkClearRules.getUuid()));
            SwCkClearRulesDTO swCkClearRulesDTO = new SwCkClearRulesDTO();
            swCkClearRulesDTO.setDatas(swCkClearRules);
            swCkClearRulesDTO.setDataDetails(listLine);
            list.add(swCkClearRulesDTO);
        }
        return list;
    }

    /**
     * 查询返回数据 格式map
     * @return
     */
    @Override
    public Map<String, String> selectRulesMap() {
        Map<String, String> map = new HashMap<>();
        List<SwCkClearRulesDTO> swCkClearRulesDTOS = this.selectRules();
        for (SwCkClearRulesDTO swCkClearRulesDTO : swCkClearRulesDTOS) {
            SwCkClearRules datas = swCkClearRulesDTO.getDatas();
            List<SwCkClearRulesLine> dataDetails = swCkClearRulesDTO.getDataDetails();
            for (SwCkClearRulesLine dataDetail : dataDetails) {
                //key:  开始日期、结束日期、清分规则、子类型、运营商，（前面几个主表条件能唯一查到）、lineCode
                String key = datas.getBeginTime()+","+datas.getEndTime()+","+datas.getClearRules()+","+
                        datas.getSubClearRules()+","+datas.getOperators()+","+dataDetail.getLineCode();
                map.put(key,dataDetail.getCountTicket());
            }
        }
        return map;
    }
	//根据日期范围，获取各种清分类型对应的各个线路的清分比例
    @Override
    public
    Map<String,String> selectRulesDetailsMapByDate(String startDate,String endDate){
       	 Map<String, String> map = new HashMap<>();
         List<SwCkClearRulesDTO> swCkClearRulesDTOS = this.selectRulesByCondition(startDate,endDate);
         for (SwCkClearRulesDTO swCkClearRulesDTO : swCkClearRulesDTOS) {
             SwCkClearRules datas = swCkClearRulesDTO.getDatas();
             List<SwCkClearRulesLine> dataDetails = swCkClearRulesDTO.getDataDetails();            
             for (SwCkClearRulesLine dataDetail : dataDetails) {
                 //key: 清分规则、子类型、运营商，（前面几个主表条件能唯一查到）、lineCode
                 String key =datas.getClearRules()+","+datas.getSubClearRules()+","+datas.getOperators()+","+dataDetail.getLineCode();
                 map.put(key,dataDetail.getCountTicket());
             }
			 if(datas.getClearRules().equals(SwCkClearRuleConstans.CLEAR_RULE_RETURN_NORMAL)||datas.getClearRules().equals(SwCkClearRuleConstans.CLEAR_RULE_RETURN_ERROR) ||datas.getClearRules().equals(SwCkClearRuleConstans.CLEAR_RULE_EMERGENCY_BIGSTREAM)){//正常退票需要到运营商级的比例
			     String key =datas.getClearRules()+","+datas.getSubClearRules()+","+datas.getOperators();
                 map.put(key,datas.getCountTicket());
			 }
             
         }
         return map;
    	
    }
    //根据日期范围，获取各种清分类型对应的运营商清分比例
    @Override
    public
    Map<String,String> selectRulesMapByDate(String startDate,String endDate){
    	Map<String, String> map = new HashMap<>();
        List<SwCkClearRulesDTO> swCkClearRulesDTOS = this.selectRulesByCondition(startDate,endDate);
        for (SwCkClearRulesDTO swCkClearRulesDTO : swCkClearRulesDTOS) {
            SwCkClearRules datas = swCkClearRulesDTO.getDatas();
            String keyMain = datas.getClearRules()+","+datas.getSubClearRules()+","+datas.getOperators();
            map.put(keyMain, datas.getCountTicket());
        }
        return map;    	
    }
	private List<SwCkClearRulesDTO> selectRulesByCondition(String startDate,String endDate) {
    	LocalDate beginTime = MyDateUtil.StringTurnLocalDate(startDate);
        LocalDate endTime = MyDateUtil.StringTurnLocalDate(endDate);
        List<SwCkClearRulesDTO> list = new ArrayList<>();
        //todo 如果传参，里边加上条件就行
        List<SwCkClearRules> swCkClearRulesList = this.list(Wrappers.<SwCkClearRules>lambdaQuery()
                .eq(SwCkClearRules::getUsedState,"1")
                .eq(SwCkClearRules::getDelFlag,"0")
                .eq(SwCkClearRules::getBeginTime,startDate)
                .eq(SwCkClearRules::getEndTime,endDate));
        
        for (SwCkClearRules swCkClearRules : swCkClearRulesList) {
            //根据UUid关联查询
            List<SwCkClearRulesLine> listLine = swCkClearRulesLineService.list(Wrappers.<SwCkClearRulesLine>lambdaQuery()
                    .eq(SwCkClearRulesLine::getRuleId,swCkClearRules.getUuid()));
            SwCkClearRulesDTO swCkClearRulesDTO = new SwCkClearRulesDTO();
            swCkClearRulesDTO.setDatas(swCkClearRules);
            swCkClearRulesDTO.setDataDetails(listLine);
            list.add(swCkClearRulesDTO);
        }
        return list;
    }

	//获取系统清分数据,根据线路
	private BigDecimal getSystemClearLongValueByLineCode( List<Map<String,Object>> listMap,String lineCode,String key) {
        if(listMap == null || listMap.isEmpty()){
            return new  BigDecimal("0");
        }
        for (Map<String,Object> map : listMap){
            if(lineCode.equals(map.get("lineCode"))) {
                return new BigDecimal(String.valueOf(map.get(key)));
            }
        }
        return new  BigDecimal("0");
    }

    /**
     * 系统清分单边销售编辑
     * @param oneSidedSalesDTO
     * @return
     */
    @Override
    public Boolean updateOneSidedSales(OneSidedSalesDTO oneSidedSalesDTO) {
        //查线路关联运营商和glineCode
        //List<Map<String,String>> lineMapList = this.baseMapper.getParamsLine();
        String nowDate = oneSidedSalesDTO.getCleanDate();//清分日期 yyyy-MM
        List<OneSidedSales> dataDetails = oneSidedSalesDTO.getDataOneSidedDetails();

        String oneDay = "-01";
        String twoDay = "02";
        String threeDay = "-03";
        String preMonth = MyDateUtil.getPreMonth(nowDate);//获取当前日期的下个月 yyyy-MM
        String maxMonthDate = MyDateUtil.getMaxMonthDate(nowDate);//获取当前日期的最后一天 yyyy-MM-dd

        LocalDate dataDate = MyDateUtil.StringTurnLocalDate(preMonth + oneDay);//清分日期 yyyy-MM-dd 次月1号
        LocalDate cleanDate = MyDateUtil.StringTurnLocalDate(preMonth + threeDay);//清分日期 yyyy-MM-dd 次月3号
        String filename = "TCONSCLEAN_" + preMonth.replaceAll("-","") + twoDay + ".dat";

        List<Tconsclean> insertTconscleanList = new ArrayList<>();
        List<SwCkSysCleaningConsType> insertOrUpdateSwCkSysCleaningConsTypeList = new ArrayList<>();


        for (OneSidedSales dataDetail : dataDetails) {
            String lineCode = dataDetail.getLineCode();
            String glineCode = dataDetail.getGlineCode();
            String serviceid = dataDetail.getServiceOrg();
            //获取当前线路对应数据
            //if(ObjectUtil.isEmpty(glineCode) || ObjectUtil.isEmpty(serviceid)){
            //    Map<String, String> lineMap = getStringValue(lineMapList, lineCode);
            //    glineCode = lineMap.get("glineCode");
            //}
            BigDecimal cleanamount = dataDetail.getMoney().multiply(new BigDecimal("100"));//金额分

            //1、插入原始表数据
            //SERVICEID,LINECODE,CleanDate,CleanAmount,dataDate 改这几个值
            //判断是否存在：filename,productIssuerId,CLEANTYPE,SERVICEID,LINECODE,CleanDate，dataDate 存在更新，不存在插入
            Tconsclean tconsclean = new Tconsclean();
            tconsclean.setFilename(filename);
            tconsclean.setProductissuerid("1");
            tconsclean.setCleantype("57");
            tconsclean.setServiceid(serviceid);
            tconsclean.setLinecode(glineCode);
            tconsclean.setDatadate(dataDate);

            LambdaQueryWrapper<Tconsclean> wrapper = Wrappers.lambdaQuery(tconsclean);
            Tconsclean tconscleanServiceOne = tconscleanService.getOne(wrapper);

            tconsclean.setCleandate(cleanDate);
            //存在更新
            if(ObjectUtil.isNotEmpty(tconscleanServiceOne)){
                tconscleanServiceOne.setCleanamount(cleanamount);
                tconscleanService.update(tconscleanServiceOne,wrapper);
            }else {//不存在插入
                tconsclean.setCleanamount(cleanamount);
                insertTconscleanList.add(tconsclean);
            }

            //2、插入业务表
            SwCkSysCleaningConsType swCkSysCleaningConsType = new SwCkSysCleaningConsType();
            swCkSysCleaningConsType.setServiceOrg(serviceid);
            swCkSysCleaningConsType.setLineCode(lineCode);
            swCkSysCleaningConsType.setProductissuerid(1);
            swCkSysCleaningConsType.setCleanType("57");
            swCkSysCleaningConsType.setTradeDate(dataDate);
            swCkSysCleaningConsType.setDelFlag("0");
            SwCkSysCleaningConsType consTypeServiceOne = swCkSysCleaningConsTypeService.getOne(Wrappers.lambdaQuery(swCkSysCleaningConsType));
            //存在更新
            if(ObjectUtil.isNotEmpty(consTypeServiceOne)){
                consTypeServiceOne.setMoney(cleanamount);
                insertOrUpdateSwCkSysCleaningConsTypeList.add(consTypeServiceOne);
            }else {//不存在插入
                swCkSysCleaningConsType.setMoney(cleanamount);
                insertOrUpdateSwCkSysCleaningConsTypeList.add(swCkSysCleaningConsType);
            }

        }

        if(CollectionUtil.isNotEmpty(insertTconscleanList)){
            tconscleanService.saveBatch(insertTconscleanList);
        }

        if(CollectionUtil.isNotEmpty(insertOrUpdateSwCkSysCleaningConsTypeList)){
            swCkSysCleaningConsTypeService.saveOrUpdateBatch(insertOrUpdateSwCkSysCleaningConsTypeList);
        }

        //3、更新系统清分数据单程票单边销售的金额
        List<SwCkSystemCleanView> updateSwCkSystemCleanViewList = new ArrayList<>();
        List<Map<String,Object>> tconscleanListMap = this.baseMapper.getTconscleanListMap(maxMonthDate);
        if(CollectionUtil.isNotEmpty(tconscleanListMap)){
            //根据上面查询出来的ONEWAY_MONEY，然后重新计算该表的TOTAL_MONEY字段
            for (Map<String, Object> objectMap : tconscleanListMap) {
                Object tradeDate = objectMap.get("TRADE_DATE");
                Object lineCode = objectMap.get("LINE_CODE");
                Object onewayMoney = objectMap.get("ONEWAY_MONEY");
                SwCkSystemCleanView viewServiceOne = swCkSystemCleanViewService.getOne(Wrappers.<SwCkSystemCleanView>lambdaQuery()
                        .eq(SwCkSystemCleanView::getLineCode, lineCode)
                        .eq(SwCkSystemCleanView::getTradeDate, tradeDate));
                if(ObjectUtil.isNotEmpty(viewServiceOne)){
                    viewServiceOne.setOnewayMoney(new BigDecimal(String.valueOf(onewayMoney)));
                    viewServiceOne.setTotalMoney(viewServiceOne.getOnewayMoney().add(viewServiceOne.getQrMoney()).add(viewServiceOne.getFaceMoney())
                            .add(viewServiceOne.getSmartCardMoney()).add(viewServiceOne.getTrafficSmartCardMoney()));
                    updateSwCkSystemCleanViewList.add(viewServiceOne);
                }
            }
        }
        if(CollectionUtil.isNotEmpty(updateSwCkSystemCleanViewList)){
            swCkSystemCleanViewService.updateBatchById(updateSwCkSystemCleanViewList);
        }
        return true;
    }

    @Override
    public List<OneSidedSales> getLineByOperator(String cleanDate) {
        String maxMonthDate = MyDateUtil.getMaxMonthDate(cleanDate);//获取当前日期的最后一天 yyyy-MM-dd
        return this.baseMapper.getLineByOperator(maxMonthDate);
    }

    private Map<String,String> getStringValue( List<Map<String,String>> listMap, String lineCode) {
        Map<String, String> hashMap = new HashMap<>();
        for (Map<String,String> map : listMap){
            if(lineCode.equals(map.get("lineCode"))) {
                hashMap.put("glineCode",map.get("glineCode"));
                hashMap.put("serviceOrg",map.get("serviceOrg"));
                return hashMap;
            }
        }
        return null;
    }
}
